package com.yf.exam.core.utils.pdf;


import com.lowagie.text.pdf.BaseFont;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.util.Map;

@Slf4j
@Component
public class PdfFileUtil {
    private static final ClassPathResource fontResource = new ClassPathResource("fonts/simsun.ttc");
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 渲染pdf文件
     *
     * @param templateName
     * @param variables
     * @return
     * @throws Exception
     */
    public byte[] generatePdf(String templateName, Map<String, Object> variables) throws Exception {
        Context context = new Context();
        context.setVariables(variables);
        // 字体路径（从 classpath 加载）
        String htmlContent = templateEngine.process(templateName, context);
        ITextRenderer renderer = new ITextRenderer();
        // 注册字体，true 表示嵌入字体
        renderer.getFontResolver().addFont(fontResource.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        renderer.setDocumentFromString(htmlContent);
        renderer.layout();

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            renderer.createPDF(out);
            return out.toByteArray();
        }
    }

}
